package com.mbt.deal.ui.adapter;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.launcher.ARouter;
import com.jungly.gridpasswordview.GridPasswordView;
import com.mbt.deal.R;
import com.mbt.deal.api.Api;
import com.mbt.deal.api.ApiServer;
import com.mbt.deal.api.RxBus;
import com.mbt.deal.api.RxResultHelper;
import com.mbt.deal.api.RxSchedulers;
import com.mbt.deal.api.RxSubscriber;
import com.mbt.deal.bean.BaseDataBean;
import com.mbt.deal.bean.OrderBean;
import com.mbt.deal.ui.fragment.DealbuinessFragment2;
import com.mbt.deal.util.ImageLoadUtil;
import com.mbt.deal.util.MyUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 * @createtime：2018/8/15 23:11
 */
public class JiaoYiAdapter extends BaseAdapter {
    private Context context;
    private List<OrderBean> lists = new ArrayList<>();
    private int type;
    Dialog dialog;

    public JiaoYiAdapter(Context context, int type) {
        this.context = context;
        this.type = type;
    }

    @Override
    public int getCount() {
        return lists.size();
    }

    @Override
    public Object getItem(int position) {
        return lists.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder vh;
        final OrderBean orderBean = lists.get(position);
        if (convertView == null) {
            convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.deal_money_iteam, parent, false);
            vh = new ViewHolder();
            vh.iv_heard = convertView.findViewById(R.id.iv_heard);
            vh.tv_create_order = convertView.findViewById(R.id.tv_create_order);
            vh.tv_one_money = convertView.findViewById(R.id.tv_one_money);
            vh.tv_count = convertView.findViewById(R.id.tv_count);
            vh.tv_name = convertView.findViewById(R.id.tv_name);
            vh.tv_money = convertView.findViewById(R.id.tv_money);
            vh.tv_create_time = convertView.findViewById(R.id.create_time);
            convertView.setTag(vh);
        } else {
            vh = (ViewHolder) convertView.getTag();
        }
        ImageLoadUtil.loadImage(orderBean.getUserHeadImage(), vh.iv_heard);
        vh.tv_name.setText(orderBean.getUserName());
        vh.tv_one_money.setText("$" + orderBean.getPrice());
        vh.tv_count.setText(orderBean.getNumber());
        vh.tv_create_time.setText("发布时间："+orderBean.getStarttime());
        vh.tv_money.setText("$" + multip(Double.parseDouble(orderBean.getPrice()),Double.parseDouble(orderBean.getNumber())));
        if (type == 1) {
            vh.tv_create_order.setText("出售");
        } else {
            vh.tv_create_order.setText("购买");
        }
        vh.tv_create_order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyUtils.hideKeyBoard(vh.tv_create_order, (Activity) context);
                checkPassword(orderBean);
            }
        });
        return convertView;
    }

    private void showDialog(final OrderBean orderBean) {
        dialog = new Dialog(context, R.style.MMyDialogstyle);
        View view = LayoutInflater.from(context).inflate(R.layout.orderdeal_dialog, null);
        dialog.setContentView(view);
        TextView tv_title = view.findViewById(R.id.tv_title);
        final TextView price = view.findViewById(R.id.price);
        final EditText et_count = view.findViewById(R.id.et_count);
        TextView tv_all = view.findViewById(R.id.tv_all);
        final TextView tv_all_price = view.findViewById(R.id.tv_all_price);
        final GridPasswordView gpv = view.findViewById(R.id.gpv);
        TextView tv_sure = view.findViewById(R.id.tv_sure);
        ImageView iv_dissmiss = view.findViewById(R.id.iv_dissmiss);
        dialog.show();
        if (type == 1) {
            tv_title.setText("向" + orderBean.getUserName() + "出售" + orderBean.getCoinName());
        } else {
            tv_title.setText("向" + orderBean.getUserName() + "购买" + orderBean.getCoinName());
        }
        price.setText(orderBean.getPrice());
        final double pprice = Double.parseDouble(orderBean.getPrice());
        final int countt = Integer.parseInt(orderBean.getNumber());
        et_count.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    tv_all_price.setText("");
                    return;
                }
                int num = Integer.parseInt(s.toString());
                if (num > countt) {
                    et_count.setText("");
                    tv_all_price.setText("");
                    Toast.makeText(context, "输入数量超过最大数量", Toast.LENGTH_SHORT).show();
                } else {
                    BigDecimal a = BigDecimal.valueOf(num);
                    BigDecimal b = BigDecimal.valueOf(pprice);
                    BigDecimal c = a.multiply(b);
                    tv_all_price.setText(c + "");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        tv_all.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                et_count.setText(orderBean.getNumber());
            }
        });
        et_count.setText(orderBean.getNumber());
        iv_dissmiss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        tv_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String count = et_count.getText().toString().trim();
                String password = gpv.getPassWord();
                if (TextUtils.isEmpty(count)) {
                    Toast.makeText(context, "请输入数量", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(password)) {
                    Toast.makeText(context, "请输入密码", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (password.length() != 6) {
                    Toast.makeText(context, "请输入正确密码", Toast.LENGTH_SHORT).show();
                    return;
                }
                orderDail(orderBean.getId() + "", count, tv_all_price.getText().toString().trim(), password);
            }
        });

    }

    private void checkPassword(final OrderBean orderBean) {
        Api.getServer(ApiServer.class).checkPassword(MyUtils.getToken(context), new HashMap<String, Object>()).compose(RxSchedulers.<BaseDataBean<String>>io_main())
                .compose(RxResultHelper.<BaseDataBean<String>>handleResult()).subscribe(new RxSubscriber<BaseDataBean<String>>(context) {
            @Override
            public void _onNext(BaseDataBean<String> stringBaseDataBean) {
                if (stringBaseDataBean.resultCode == 0) {
                    showDialog(orderBean);
                } else {
                    Toast.makeText(context, "请设置交易密码", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void _onError(String message) {
                ARouter.getInstance().build("/personal/TradingPwdSettingActivity").navigation();
            }

            @Override
            public void onCompleted() {

            }
        });
    }

    private void orderDail(String pid, String num, String price, String password) {
        Map map = new HashMap();
        map.put("pid", pid);
        map.put("number", num);
        map.put("numberpwd", password);
        if (type == 2) {
            Api.getServer(ApiServer.class).buyorder(MyUtils.getToken(context), map).compose(RxSchedulers.<BaseDataBean<String>>io_main()).compose(RxResultHelper.<BaseDataBean<String>>handleResult())
                    .subscribe(new RxSubscriber<BaseDataBean<String>>(context) {
                        @Override
                        public void _onNext(BaseDataBean<String> stringBaseDataBean) {
                            Toast.makeText(context, "交易成功", Toast.LENGTH_SHORT).show();
                            dialog.dismiss();
                            RxBus.getInstance().post(DealbuinessFragment2.DEALBUINESSFRAGMENTRXBUS, "");
                        }

                        @Override
                        public void _onError(String message) {

                        }

                        @Override
                        public void onCompleted() {

                        }
                    });
        } else if (type == 1) {
            Api.getServer(ApiServer.class).saleorder(MyUtils.getToken(context), map).compose(RxSchedulers.<BaseDataBean<String>>io_main()).compose(RxResultHelper.<BaseDataBean<String>>handleResult())
                    .subscribe(new RxSubscriber<BaseDataBean<String>>(context) {
                        @Override
                        public void _onNext(BaseDataBean<String> stringBaseDataBean) {
                            Toast.makeText(context, "交易成功", Toast.LENGTH_SHORT).show();
                            dialog.dismiss();
                            RxBus.getInstance().post(DealbuinessFragment2.DEALBUINESSFRAGMENTRXBUS, "");
                        }

                        @Override
                        public void _onError(String message) {

                        }

                        @Override
                        public void onCompleted() {

                        }
                    });
        }
    }

    public void setLists(List<OrderBean> lists, int type) {
        if (this.lists == null) {
            this.lists = new ArrayList<>();
        }
        this.type = type;
        this.lists.clear();
        this.lists.addAll(lists);
        notifyDataSetChanged();
    }

    public void addLists(List<OrderBean> lists) {
        if (this.lists == null) {
            this.lists = new ArrayList<>();
        }
        this.lists.addAll(lists);
        notifyDataSetChanged();
    }

    public class ViewHolder {
        public ImageView iv_heard;
        public TextView tv_name;
        public TextView tv_one_money;
        public TextView tv_count;
        public TextView tv_money;
        public TextView tv_create_order;
        public TextView tv_create_time;
    }
    private double multip(double a, double b) {
        BigDecimal a1 = BigDecimal.valueOf(a);
        BigDecimal b1 = BigDecimal.valueOf(b);
        BigDecimal c = a1.multiply(b1);
        return c.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
    }
}
